import re
from django.contrib.auth.backends import ModelBackend

from users.models import User


# 注: 若想对payload中的内容进行修改,那么需要考虑api_settings.JWT_PAYLOAD_HANDLER,具体应是修改/重写jwt_payload_handler方法(utils.py文件中),看源码
# def jwt_payload_handler(user):
#     pass


# ---------------------------更改视图函数的返回值---------------------------------
# 重写此方法,返回响应值
def jwt_response_payload_handler(token, user=None, request=None):
    print(token)
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


# ---------------------------多账号登录实现后端---------------------------------
def get_user_by_account(account):
    """
    根据账号获取user对象
    :param account: 账号,可以是用户名,也可以是手机号
    :return: User对象或者None
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证,username为用户名或手机号
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        # user.check_password用户模型默认的校验密码方法
        if user is not None and user.check_password(password):
            return user

